import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/views/Layout.vue'
import Login from '@/views/login/index.vue'
import Home from '@/views/home/index.vue'
import Question from '@/views/question/index.vue'
import Video from '@/views/video/index.vue'
import User from '@/views/user/index.vue'
import store from '@/store/index.js'
import Search from '@/views/search/Search.vue'
import Result from '@/views/search/result.vue'
import Detail from '@/views/detail/index.vue'
import Profile from '@/views/user/profile.vue'
import Chat from '@/views/user/chat.vue'

Vue.use(VueRouter)

const routes = [{
  path: '/',
  name: 'Layout',
  component: Layout,
  redirect: '/home',
  children: [{
    path: '/home',
    component: Home
  },
  {
    path: '/user',
    component: User
  },
  {
    path: '/question',
    component: Question
  },
  {
    path: '/video',
    component: Video
  }
  ]
},
{
  path: '/login',
  name: 'Login',
  component: Login
},
{
  path: '/search',
  name: 'Search',
  component: Search
},
{
  path: '/result/:kw',
  name: 'Result',
  component: Result,
  props: true
},
{
  path: '/detail/:id',
  name: 'Detail',
  component: Detail,
  props: true
},
{
  path: '/profile',
  component: Profile
},
{
  path: '/chat',
  component: Chat
}
]

const router = new VueRouter({
  routes
})

// 白名单列表（没有登录也可以访问）
const whiteList = ['/home', '/video']
router.beforeEach((to, from, next) => {
  const userInfo = store.state.login.userinfo
  // console.log(userInfo)
  if (to.path === '/login') {
    // 访问登录页面
    next()
  } else if (userInfo && userInfo.token && userInfo.refresh_token) {
    // 访问非登录页面，并且有token
    next()
  } else if (whiteList.includes(to.path)) {
    // 访问非登录页面，但是没有token，并且
    // 判断访问的路由路径是否在白名单里面
    next()
  } else {
    // 访问非登录页面，但是没有token，也不在白名单里面
    next('/login')
  }
})
export default router
